package com.ufo.store.management.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.ufo.store.management.R;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;


/**
 * Created by Administrator on 2016/3/23.
 */
public class VoiceActivity extends Activity implements View.OnClickListener {
    private RelativeLayout rl_translate_recording_voice_cancel, rl_translate_recording_voice_submit;
    // 语音听写对象
    private SpeechRecognizer mIat;
    public String transferType = "zh_cn";
    private String TAG = "Voice_Activity";
    private Drawable[] micImages;
    private ImageView mTranslateRecordingVoiceImg;
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_voice);
        // 动画资源文件,用于录制语音时
        micImages = new Drawable[]{
                getResources().getDrawable(R.drawable.voice_00),
                getResources().getDrawable(R.drawable.voice_00),
                getResources().getDrawable(R.drawable.voice_00),
                getResources().getDrawable(R.drawable.voice_00),
                getResources().getDrawable(R.drawable.voice_01),
                getResources().getDrawable(R.drawable.voice_02),
                getResources().getDrawable(R.drawable.voice_03),
                getResources().getDrawable(R.drawable.voice_04),
                getResources().getDrawable(R.drawable.voice_04),
                getResources().getDrawable(R.drawable.voice_04),
                getResources().getDrawable(R.drawable.voice_05),
                getResources().getDrawable(R.drawable.voice_05),
                getResources().getDrawable(R.drawable.voice_05),
                getResources().getDrawable(R.drawable.voice_05),
                getResources().getDrawable(R.drawable.voice_05),
                getResources().getDrawable(R.drawable.voice_05),};
        rl_translate_recording_voice_cancel = (RelativeLayout) findViewById(R.id.rl_translate_recording_voice_cancel);
        rl_translate_recording_voice_submit = (RelativeLayout) findViewById(R.id.rl_translate_recording_voice_submit);
        rl_translate_recording_voice_cancel.setOnClickListener(this);
        rl_translate_recording_voice_submit.setOnClickListener(this);
        mTranslateRecordingVoiceImg = (ImageView) findViewById(R.id.translate_recording_voice_img); //话筒半圆

        // 初始化识别无UI识别对象
        // 使用SpeechRecognizer对象，可根据回调消息自定义界面；
        mIat = SpeechRecognizer.createRecognizer(this, mInitListener);
        setParam();
        mIat.startListening(recognizerListener);
    }

    public String result = "";
    //监听器
    private RecognizerListener recognizerListener = new RecognizerListener() {
        //volume音量值0~30， data音频数据
        @Override
        public void onVolumeChanged(int i, byte[] bytes) {
            mTranslateRecordingVoiceImg
                    .setImageDrawable(micImages[i / 2]);
        }

        //开始录音
        @Override
        public void onBeginOfSpeech() {

        }

        //结束录音
        @Override
        public void onEndOfSpeech() {

        }

        //一般情况下会通过onResults接口多次返回结果，完整的识别内容是多次结果的累加；
        //关于解析Json的代码可参见Demo中JsonParser类；
        //isLast等于true时会话结束。
        @Override
        public void onResult(RecognizerResult recognizerResult, boolean isLast) {
            result = result + getStringResult(recognizerResult);
            if (isLast) {
                Intent intent = new Intent();
                intent.putExtra("result", result);
                setResult(RESULT_OK, intent);
                finish();
            }
        }

        //会话发生错误回调接口
        // Tips：
        // 错误码：10118(您没有说话)，可能是录音机权限被禁，需要提示用户打开应用的录音权限。
        // 如果使用本地功能（语记）需要提示用户开启语记的录音权限。
        @Override
        public void onError(SpeechError speechError) {
            if ("10118".equals(speechError.getPlainDescription(true))) {
                Toast.makeText(VoiceActivity.this, "您没有说话", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(VoiceActivity.this, "异常" + speechError.getPlainDescription(true), Toast.LENGTH_LONG).show();
            }
            finish();
        }

        //扩展用接口
        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {

        }
    };

    private String getStringResult(RecognizerResult results) {
        String json = results.getResultString();
        StringBuffer ret = new StringBuffer();
        try {
            JSONTokener tokener = new JSONTokener(json);
            JSONObject joResult = new JSONObject(tokener);

            JSONArray words = joResult.getJSONArray("ws");
            for (int i = 0; i < words.length(); i++) {
                // 转写结果词，默认使用第一个结果
                JSONArray items = words.getJSONObject(i).getJSONArray("cw");
                JSONObject obj = items.getJSONObject(0);
                ret.append(obj.getString("w"));
//				如果需要多候选结果，解析数组其他字段
//				for(int j = 0; j < items.length(); j++)
//				{
//					JSONObject obj = items.getJSONObject(j);
//					ret.append(obj.getString("w"));
//				}
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret.toString();
    }

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            Log.d(TAG, "SpeechRecognizer init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                Log.d(TAG, "初始化失败");
            }
        }
    };

    private void setParam() {
// 清空参数
        mIat.setParameter(SpeechConstant.PARAMS, null);

        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");


        // 设置语言
        mIat.setParameter(SpeechConstant.LANGUAGE, transferType);
        if (transferType.equals("zh_cn")) {
            // 设置语言区域
            mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
        }


        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(SpeechConstant.VAD_BOS, "4000");

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mIat.setParameter(SpeechConstant.VAD_EOS, "1000");

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, "0");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        //  mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        //  mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/iat.wav");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_translate_recording_voice_cancel:
                mIat.stopListening();
                finish();
                break;
            case R.id.rl_translate_recording_voice_submit:
                mIat.stopListening();
                finish();
                break;
        }
    }
}
